package com.wangxin.study8.threadtest;

/**
 * @ClassName DeadLockDemo
 * @Description 死锁demo
 * @Author jojo.wang
 * @Date 2019-05-19 15:43
 * @Version 1.0
 **/
public class DeadLockDemo {
    private static Object res1 = new Object();
    private static Object res2 = new Object();

    public static void main(String[] args) {
        new Thread(()->{
            synchronized (res1){
                System.out.println(Thread.currentThread()+"get res1");
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread()+"waiting get res2");
                synchronized (res2){
                    System.out.println(Thread.currentThread()+"get res2");
                }
            }
        },"线程1").start();

        //不发生死锁
        new Thread(()->{
            synchronized (res1){
                System.out.println(Thread.currentThread()+"get res1");
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "waiting get resource2");
                synchronized (res2){
                    System.out.println(Thread.currentThread() + "get resource2");
                }
            }
        },"线程2").start();

        //死锁
        new Thread(()->{
            synchronized (res2){
                System.out.println(Thread.currentThread()+"get res2");
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread()+"waiting get res1");
                synchronized (res1){
                    System.out.println(Thread.currentThread()+"get res1");
                }
            }
        },"线程2").start();
    }
}
